﻿@model Amazon.Checkout.ViewModels.TaxNewUpdateViewModel

@{ Script.Require("JQuery").AtHead(); }

<h1>@T((Model.TaxTableId == null || Model.TaxTableId == 0) ? "New Tax Table" : "Edit Tax Table")</h1>

@using (Html.BeginFormAntiForgeryPost())
{
    if (Model.TaxTableId != null)
    {
        @Html.HiddenFor(m => m.TaxTableId)
    }
    @Html.ValidationSummary()

    <fieldset> 
        @Html.LabelFor(tax => tax.Name, T("Tax Table Name:")) 
        @Html.TextBoxFor(tax => tax.Name, new { @class = "text" })
    </fieldset>

    <fieldset>
        <button class="primaryAction" type="submit">@T((Model.TaxTableId == null || Model.TaxTableId == 0) ? "Create Tax Table" : "Update Tax Table")</button>
    </fieldset>
    
    if (Model.TaxTableId != null && Model.TaxTableId > 0)
    {
        <h2>Tax Rules</h2>        
    
        <label for="RegionType">@T("Region Type:")</label>
    
        @Html.RadioButton("RegionType", "US State Region", true, new { id = "radio-usstate-region" }) <span style="vertical-align:top;">@T("US State Region")</span>
        @Html.RadioButton("RegionType", "US Zip Region", false, new { id = "radio-uszip-region" })<span style="vertical-align:top;">@T("US Zip Region")</span>
        @Html.RadioButton("RegionType", "Predefined Region", false, new { id = "radio-predefined-region" })<span style="vertical-align:top;">@T("Predefined Region")</span>
        @Html.RadioButton("RegionType", "World Region", false, new { id = "radio-world-region" })<span style="vertical-align:top;">@T("World Region")</span>
        @Html.RadioButton("RegionType", "Postal Region", false, new { id = "radio-postal-region" })<span style="vertical-align:top;">@T("Postal Region")</span>

        <label for="Region">@T("US State Region")</label>
        @Html.TextBox("Region", string.Empty, new { @class = "text" })

        <label for="Rate">@T("Rate")</label>
        @Html.TextBox("Rate", string.Empty, new { @class = "text" })<em>&nbsp;@T("(0.000001 to 0.15)")</em>

        <input type="hidden" value="@Model.TaxRuleIds" name="TaxRuleIds" id="TaxRuleIds" />
    
        <fieldset class="with-checkbox">
            <span>
                @Html.CheckBox("IsShippingTaxed")
                <label for="IsShippingTaxed" class="forcheckbox">@T("Is Shipping Taxed")</label>
            </span>        
        </fieldset>
    
        <button class="primaryAction" type="button">@T("Add Tax Rule")</button>    
        <fieldset>
            <table class="items" summary="@T("Tax rule list.")">
                <colgroup>
                    <col id="Col1" />
                    <col id="Col2" />
                    <col id="Col3" />
                    <col id="Col4" />
                    <col id="Col5" />
                </colgroup>
                <thead>
                    <tr>
                        <th scope="col">@T("RegionType")</th>
                        <th scope="col">@T("Region")</th>
                        <th scope="col">@T("Tax Rate")</th>
                        <th scope="col">@T("Is Shipping Taxed")</th>
                        <th scope="col">@T("Actions")</th>
                    </tr>
                </thead>

                @if (Model.TaxRules != null && Model.TaxRules.Count() > 0)
                {
                    foreach (var taxTable in Model.TaxRules)
                    {
                        <tr class="tax-rule">              
                            <td>@taxTable.RegionType</td>
                            <td>@taxTable.Region</td>
                            <td>@taxTable.Rate</td>
                            <td>@taxTable.IsShippingTaxed</td>
                            <td><a class="delete-tax-rule" style="cursor:pointer;" rel="@taxTable.Id">@T("Delete")</a></td>
                        </tr>
                    }
                    <tr class="no-records" style="display:none;">
                        <td colspan="5">@T("There are no tax rules associated to the tax table.")</td>
                    </tr>
                }
                else
                { 
                    <tr class="no-records">
                        <td colspan="5">@T("There are no tax rules associated to the tax table.")</td>
                    </tr>                 
                }
            </table>
        </fieldset>
                                                                                                                                                                                                            
        <script type="text/javascript">
            $(document).ready(function () {
                $("button[type='button']").click(function () {
                    var regionType = $("input[name='RegionType']:checked").val();
                    var region = $("#Region").val();
                    var rate = $("#Rate").val();
                    var shippingTaxed = $("#IsShippingTaxed").is(':checked').toString();

                    $.post('@Url.Action("New", "TaxRule")',
                            { 
                                regionType: regionType, 
                                region: region, 
                                rate: rate, 
                                shippingTaxed: shippingTaxed, 
                                "__RequestVerificationToken": '@Html.AntiForgeryTokenValueOrchard()' 
                            },
                            function (taxRule) {
                                if (taxRule.error){
                                    alert(taxRule.error);
                                    return false;
                                 }
                                 $("table.items tr.no-records").hide();

                                 var actionPattern = '@Html.ActionLink("text", "action", new { taxTableId = "id" })';

                                 var row = $("<tr>").addClass('tax-rule')
                                                    .append($('<td>').text(taxRule.RegionType))
                                                    .append($('<td>').text(taxRule.Region))
                                                    .append($('<td>').text(taxRule.Rate))
                                                    .append($('<td>').text(taxRule.IsShippingTaxed))
                                                    .append($('<td>').html('<a class="delete-tax-rule" style="cursor:pointer;" rel="'+ taxRule.Id +'">Delete</a>'));

                                 var taxRuleIds = $("#TaxRuleIds").val();
                                 taxRuleIds += ($.trim(taxRuleIds).length == 0) ? taxRule.Id : ", " + taxRule.Id;
                                 $("#TaxRuleIds").val(taxRuleIds);

                                 $("table.items tbody").append(row);
                                 $("#Region").val('');
                                 $("#Rate").val('');
                                 $("#IsShippingTaxed").removeAttr('checked');

                                 $.post('@Url.Action("Update", "TaxTable")',
                                                     { 
                                                        taxTableId: @Model.TaxTableId, 
                                                        name: $("#Name").val(), 
                                                        taxRuleIds: taxRuleIds, 
                                                        "__RequestVerificationToken": '@Html.AntiForgeryTokenValueOrchard()' 
                                                     },
                                     function (taxTable) { }, "json");
                             }, "json");
                });

                $(".delete-tax-rule").live('click', function(){
                    var link = $(this);
                    $.ajax({
                        url: '@Url.Action("Delete", "TaxRule")',
                        data: 
                            { 
                                taxRuleId: link.attr('rel'), 
                                "__RequestVerificationToken": '@Html.AntiForgeryTokenValueOrchard()' 
                            },
                        context: document.body,
                        success: function(data){
                            link.closest('tr').remove();
                
                            var numberOfRules = $("table.items tr.tax-rule").length;
                
                            if (numberOfRules == 0)
                                $("table.items tr.no-records").show();                        
                        },
                        error: function(e) {console.log(e)}
                    });
                });

                $("input[type='radio']").each(function () {
                    $(this).change(function () {
                        switch ($(this).val()) {
                            case "US State Region":
                                $("label[for='Region']").text('US State Region:');
                                break;
                            case "US Zip Region":
                                $("label[for='Region']").text('US Zip Region:');
                                break;
                            case "Predefined Region":
                                $("label[for='Region']").text('Predefined Region:');
                                break;
                            case "World Region":
                                $("label[for='Region']").text('World Region:');
                                break;
                            case "Postal Region":
                                $("label[for='Region']").text('Postal Region:');
                                break;
                            default:
                                $("label[for='Region']").text('US State Region:');
                        }
                    });
                })
            });
        </script>
    }
}
